package com.hfb.mashibing.alip8.juc.c008;


import java.util.concurrent.TimeUnit;

/** 面试题:
 * 模拟银行账户：对业务写方法加锁，对业务读方法不加锁，这样行不行？
 * 答：不行，容易产生脏读(dirtyRead)问题
 *      但是，如果业务可以忍受脏读的话，
 *          这么干，可以加快效率(最低提高2个数量级)
 */
public class Account {

    String name;
    double balance;
    public synchronized void set(String name, double balance) {
        System.out.println(Thread.currentThread().getName()+" set start...");
        this.name = name;
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.balance = balance;
        System.out.println(Thread.currentThread().getName()+" set end...");
    }

    public /*synchronized*/ double getBalance() {
        return this.balance;
    }

    public static void main(String[] args) {
        Account a = new Account();

        new Thread(()->{a.set("zhang shan", 100.0);}).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(a.getBalance());

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(a.getBalance());

    }
}
